package com.cell.foodie.back.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 登录拦截器
 * 
 * @author huhu
 *
 */
public class LoginInterceptor implements HandlerInterceptor{

  @Override
  public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
      throws Exception {
    // TODO Auto-generated method stub
    System.out.println("视图渲染之后执行1");
  }

  @Override
  public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
      throws Exception {
    // TODO Auto-generated method stub
    System.out.println("执行控制器之后执行1");
    
  }

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
    System.out.println("执行控制器之前执行1");
    HttpSession session = request.getSession();
    String loginUrl = request.getRequestURI();//获取当前地址栏的url
    
    /*
     * 拦截除登录页面的所有页面
     * 判断条件：session不存在并且不是登录页面
     * 是：重定向到登录页面
     * 否：不拦截
     */
    if (session.getAttribute("login_mession") == null && !loginUrl.equals("/foodie/admin_login/view")&& !loginUrl.equals("/foodie/admin_login/login")) {
   
      response.sendRedirect("/foodie/admin_login/view");// 用户未登录,重定向到登录页面
      
    }
    
    return true;
  }

}
